package ch01.team;

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class TeamsUtility {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TeamsUtility tu = new TeamsUtility();
		tu.make_test_teams();
	}

	private Map<String, Team> team_map;

	public TeamsUtility() {
		team_map = new HashMap<String, Team>();
	}

	public Team getTeam(String name) {
		return team_map.get(name);
	}

	public ArrayList<Team> getTeams() {
		List<Team> list = new ArrayList<Team>();
		Set<String> keys = team_map.keySet();
		for (String key : keys)
			list.add(team_map.get(key));
		return (ArrayList<Team>) list;
	}

	public void make_test_teams() {
		List<Team> teams = new ArrayList<Team>();
		Player chico = new Player("Leonard Marx", "Chico");
		Player groucho = new Player("Julius Marx", "Groucho");
		Player harpo = new Player("Adolph Marx", "Harpo");
		List<Player> mb = new ArrayList<Player>();
		mb.add(chico);
		mb.add(groucho);
		mb.add(harpo);
		Team marx_brothers = new Team("Marx Brothers", mb);
		//List<Team> teams = new ArrayList<Team>();
		Player chico1 = new Player("Leonard Marx1", "Chico1");
		Player groucho1 = new Player("Julius Marx1", "Groucho1");
		Player harpo1 = new Player("Adolph Marx1", "Harpo1");
		List<Player> mb1 = new ArrayList<Player>();
		mb.add(chico1);
		mb.add(groucho1);
		mb.add(harpo1);
		Team marx_brothers1 = new Team("Marx Brothers1", mb1);
		teams.add(marx_brothers);
		teams.add(marx_brothers1);
		store_teams(teams);
		serializeTeams(teams);
	}

	public void serializeTeams(List<Team> teams) {
		String sep = System.getProperty("file.separator");
		// File serializedFile = new
		// File("D://scdjws//scdjwsApp//jwsUpnRunning//src//restFul//teams//teams.ser");
		File serializedFile = new File("C:" + sep + "navneet" + sep
				+ "scdjwsApps" + sep + "jwsUpnRunning" + sep + "src" + sep + ""
				+ "ch01" + sep + "team" + sep + "teams.ser");
		try {
			FileOutputStream fos = new FileOutputStream(serializedFile);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			XMLEncoder xmlEncoder = new XMLEncoder(bos);
			xmlEncoder.writeObject(teams);
			xmlEncoder.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace(); // TODO: handle exception
		}
	}

	private void store_teams(List<Team> teams) {
		for (Team team : teams)
			team_map.put(team.getName(), team);
	}

}
